import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

export const useAuthStore = defineStore('auth', () => {
  const isAuthenticated = ref(false)
  const user = ref(null)
  const router = useRouter()

  function login(username, password) {
    // 模拟登录请求
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (username === 'admin' && password === 'admin123') {
          isAuthenticated.value = true
          user.value = { 
            username: 'admin', 
            name: '管理员',
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
          }
          localStorage.setItem('isAuthenticated', 'true')
          resolve()
        } else {
          reject(new Error('用户名或密码错误'))
        }
      }, 800)
    })
  }

  function logout() {
    isAuthenticated.value = false
    user.value = null
    localStorage.removeItem('isAuthenticated')
    router.push({ name: 'Login' })
  }

  function checkAuth() {
    const auth = localStorage.getItem('isAuthenticated')
    if (auth === 'true') {
      isAuthenticated.value = true
      user.value = { 
        username: 'admin', 
        name: '管理员',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
    }
  }

  return { isAuthenticated, user, login, logout, checkAuth }
})